<template>
  <el-row :gutter="20" class="app-container">
    <Splitpanes>
      <pane size="16" v-if="$auth.hasRoleOr(['admin','manager','fishingceo'])">
        <el-col>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
      </pane>
      <pane :size="$auth.hasRoleOr(['admin','manager','fishingceo']) ? 84 : 100">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="订单编号" prop="orderId">
            <el-input
              v-model="queryParams.orderId"
              placeholder="请输入订单编号"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="鱼塘" prop="pondId">
            <el-select
              v-model="queryParams.pondId"
              @change="handleQuery"
              placeholder="选择鱼塘"
              style="width: 120px"
              clearable
            >
              <el-option
                v-for="item in pondOptionList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pond:pondReview:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pond:pondReview:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pondReviewList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <el-table-column label="所属钓场" align="center" prop="deptName" />
      <el-table-column label="鱼塘" align="center" prop="pondName" />
      <el-table-column label="评价用户" align="center" prop="userName" />
      <el-table-column label="评分" align="center" prop="score" />
      <el-table-column label="评价内容" align="center" prop="content" />
      <el-table-column label="评价图片" align="center" width="120">
        <template #default="scope">
          <div v-if="getImageUrls(scope.row.imageList).length > 0">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewImages(scope.row.imageList)"
              style="font-size: 12px;"
            >
              查看图片({{ getImageUrls(scope.row.imageList).length }})
            </el-button>
          </div>
          <span v-else style="color: #999;">无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pond:pondReview:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pond:pondReview:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改鱼塘评价对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="pondReviewRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属钓场" prop="deptId">
          <DeptSelect
            v-model="form.deptId"
            @change="handleDeptChange"
          />
        </el-form-item>
        <el-form-item label="所属鱼塘" prop="pondId">
          <el-select
            v-model="form.pondId"
            placeholder="选择鱼塘"
            style="width: 100%"
          >
            <el-option
              v-for="item in formPondOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="评价用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入评价用户ID" />
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-rate v-model="form.score" :max="5" show-score />
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="评价图片">
          <image-upload v-model="form.images" :limit="9" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片查看弹窗 -->
    <el-dialog 
      title="查看评价图片" 
      v-model="imageViewerOpen" 
      width="80%" 
      append-to-body
      :close-on-click-modal="true"
    >
      <div class="image-viewer-container">
        <el-image
          v-for="(imageUrl, index) in currentViewImages"
          :key="index"
          :src="imageUrl"
          :preview-src-list="currentViewImages"
          :initial-index="index"
          fit="contain"
          style="width: 200px; height: 200px; margin: 10px; border-radius: 8px; cursor: pointer;"
          preview-teleported
        />
      </div>
      <div v-if="currentViewImages.length === 0" style="text-align: center; color: #999; padding: 50px;">
        暂无图片
      </div>
    </el-dialog>
      </pane>
    </Splitpanes>
  </el-row>
</template>

<script setup name="PondReview">
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { useDeptTree } from "@/utils/deptTreeUtils";
import { listPond } from "@/api/pond/pond";
import { listPondReview, getPondReview, delPondReview, addPondReview, updatePondReview } from "@/api/pond/pondReview"
import DeptSelect from "@/components/DeptSelect/index.vue";

const { proxy } = getCurrentInstance()

const pondReviewList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 图片查看相关
const imageViewerOpen = ref(false)
const currentViewImages = ref([])

// 使用部门树工具
const {
  deptOptions,
  enabledDeptOptions,
  getDeptTree,
  handleFormDeptNodeClick,
  handleSidebarDeptNodeClick,
} = useDeptTree();

const pondOptionList = ref([]);
const formPondOptionList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    pondId: null,
    userId: null,
    score: null,
    content: null,
    orderId: null,
  },
  rules: {
    orderId: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "所属钓场不能为空", trigger: "blur" }
    ],
    pondId: [
      { required: true, message: "所属鱼塘不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "评价用户ID不能为空", trigger: "blur" }
    ],
    score: [
      { required: true, message: "评分不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data);

/** 获取图片URL数组 - 兼容不同的数据格式 */
function getImageUrls(images) {
  if (!images) return [];
  
  if (Array.isArray(images)) {
    // 如果是对象数组格式 [{imageUrl: "xxx"}, {imageUrl: "yyy"}]
    return images.map(item => item.imageUrl || item).filter(url => url);
  } else if (typeof images === 'string' && images.trim()) {
    // 如果是字符串格式 "url1,url2,url3"
    return images.split(',').map(url => url.trim()).filter(url => url);
  }
  
  return [];
}

/** 查看图片 */
function viewImages(images) {
  currentViewImages.value = getImageUrls(images);
  imageViewerOpen.value = true;
}

/** 查询鱼塘评价列表 */
function getList() {
  loading.value = true
  listPondReview(queryParams.value).then(response => {
    pondReviewList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderId: null,
    deptId: null,
    pondId: null,
    userId: null,
    score: null,
    content: null,
    images: "",
    createTime: null,
    updateTime: null
  }
  formPondOptionList.value = [];
  proxy.resetForm("pondReviewRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef && proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 部门选择变化事件 */
function handleDeptChange(deptId) {
  // 当部门改变时，重新加载对应的鱼塘列表
  if (deptId) {
    const params = {
      pageNum: 1,
      pageSize: 1000,
      deptId: deptId,
    };
    listPond(params).then((response) => {
      formPondOptionList.value = response.rows || [];
      form.value.pondId = null; // 清空鱼塘选择
    });
  } else {
    formPondOptionList.value = [];
    form.value.pondId = null;
  }
}

/** 侧边栏部门树节点单击事件 */
function handleNodeClick(data) {
  handleSidebarDeptNodeClick(data, (deptId) => {
    queryParams.value.deptId = deptId;
    handleQuery();
  });
}

/** 获取鱼塘选项 */
function getOptions() {
  if (queryParams.value.deptId) {
    const params = {
      pageNum: 1,
      pageSize: 1000,
      deptId: queryParams.value.deptId,
    };
    listPond(params).then((response) => {
      pondOptionList.value = response.rows || [];
    });
  } else {
    pondOptionList.value = [];
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 设置默认部门为左侧树选中的部门
  form.value.deptId = queryParams.value.deptId;
  // 如果有选中的部门，获取对应的鱼塘列表
  if (form.value.deptId) {
    const params = {
      pageNum: 1,
      pageSize: 1000,
      deptId: form.value.deptId,
    };
    listPond(params).then((response) => {
      formPondOptionList.value = response.rows || [];
    });
  }
  open.value = true
  title.value = "添加鱼塘评价"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPondReview(_id).then(response => {
    form.value = response.data
    
    // 处理图片数据格式转换
    if (form.value.images) {
      if (Array.isArray(form.value.images)) {
        // 如果后端返回的是对象数组，转换为字符串格式供image-upload组件使用
        form.value.images = form.value.images
          .map(item => item.imageUrl || item)
          .filter(url => url)
          .join(',');
      } else if (typeof form.value.images !== 'string') {
        form.value.images = "";
      }
    } else {
      form.value.images = "";
    }
    
    // 如果有部门ID，加载对应的鱼塘列表
    if (form.value.deptId) {
      const params = {
        pageNum: 1,
        pageSize: 1000,
        deptId: form.value.deptId,
      };
      listPond(params).then((pondResponse) => {
        formPondOptionList.value = pondResponse.rows || [];
      });
    }
    
    open.value = true
    title.value = "修改鱼塘评价"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pondReviewRef"].validate(valid => {
    if (valid) {
      // 准备提交数据，转换图片格式
      const submitData = { ...form.value };
      
      // 将图片字符串转换为后端需要的对象数组格式
      if (submitData.images && typeof submitData.images === 'string') {
        const imageUrls = submitData.images.split(',').filter(url => url.trim());
        submitData.images = imageUrls.map(imageUrl => ({
          imageUrl: imageUrl.trim()
        }));
      } else if (!submitData.images) {
        submitData.images = [];
      }
      
      if (form.value.id != null) {
        updatePondReview(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPondReview(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除鱼塘评价编号为"' + _ids + '"的数据项？').then(function() {
    return delPondReview(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pond/pondReview/export', {
    ...queryParams.value
  }, `pondReview_${new Date().getTime()}.xlsx`)
}

// 监听部门选择变化
watch(
  () => queryParams.value.deptId,
  (newVal) => {
    getOptions();
  }
);


getDeptTree();
getList();
</script>

<style scoped>
.image-viewer-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  gap: 10px;
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.image-viewer-container .el-image {
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
}

.image-viewer-container .el-image:hover {
  border-color: #409eff;
  transform: scale(1.05);
}
</style>
